package com.cloud.elm.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.cloud.elm.feign.BusinessFeignClient;
import com.cloud.elm.feign.DaFeignClient;
import com.cloud.elm.feign.UserFeignClient;
import com.cloud.elm.po.*;
import com.cloud.elm.po.vo.BusinessOrderVO;
import com.cloud.elm.service.OrdersService;
import com.cloud.elm.utils.CommonUtil;
import com.cloud.elm.utils.response.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("/elm/OrdersController")
public class OrdersController {

	@Autowired
	private OrdersService ordersService;

	@Autowired
	private UserFeignClient userFeignClient;

	@Autowired
	private BusinessFeignClient businessFeignClient;

	@Autowired
	private DaFeignClient daFeignClient;

//	@Autowired
//	private RestTemplate restTemplate;

	@PostMapping("/createOrders/{userId}/{businessId}/{daId}/{orderTotal}")
	public ResultBody<Integer> createOrders(@PathVariable("userId") String userId,
											@PathVariable("businessId") String businessId,
											@PathVariable("daId") Integer daId,
											@PathVariable("orderTotal") Double orderTotal) {
		Orders orders = new Orders();
		try {
			orders.setUserId(userId);
			orders.setBusinessId(businessId);
			orders.setDaId(daId);
			orders.setOrderTotal(orderTotal);
			orders.setOrderDate(CommonUtil.getCurrentDate());
			return ResultBody.success("添加订单成功！", ordersService.createOrders(orders));
		} catch (Exception e) {
			return ResultBody.error("添加订单失败！", -1);
		}
	}
	
	@GetMapping("/getOrdersById/{orderId}")
	public ResultBody<JSONObject> getOrdersById(@PathVariable("orderId") Integer orderId) {
		try {
			Orders orders = ordersService.getOrdersById(orderId);
			if (orders == null) {
				return ResultBody.error("不存在此订单！", null);
			}

			DeliveryAddress da = com.alibaba.fastjson.JSONObject.parseObject
					(JSON.toJSONString(daFeignClient.getDeliveryAddressById(orders.getDaId())), DeliveryAddress.class);

//			String daUrl = "http://localhost:10500/elm/DeliveryAddressController/getDeliveryAddressById/" + orders.getDaId();
//			DeliveryAddress da = com.alibaba.fastjson.JSONObject.parseObject(parseDataToObjStr(daUrl), DeliveryAddress.class);

			String address = da.getAddress();

			Business business = com.alibaba.fastjson.JSONObject.parseObject
					(JSON.toJSONString(businessFeignClient.getBusinessById(orders.getBusinessId())), Business.class);

//			String businessUrl = "http://localhost:10300/elm/BusinessController/getBusinessById/" + orders.getBusinessId();
//			Business business = com.alibaba.fastjson.JSONObject.parseObject(parseDataToObjStr(businessUrl), Business.class);

			List<OrderDetailet> detailets = ordersService.getOrderDetailetByOrderId(orders.getOrderId());
			List<BusinessOrderVO> businessOrderVOList = new ArrayList<>();

			JSONObject object = new JSONObject();

			for (OrderDetailet detailet : detailets) {
				BusinessOrderVO businessOrderVO = BusinessOrderVO.builder()
						.foodName(detailet.getFoodName())
						.foodPrice(detailet.getFoodPrice())
						.quantity(detailet.getQuantity()).build();
				businessOrderVOList.add(businessOrderVO);
			}

			object.putOpt("address", address);
			object.putOpt("totalPrice", orders.getOrderTotal());
			object.putOpt("deliveryPrice", business.getDeliveryPrice());
			object.putOpt("priceDetails", businessOrderVOList);

			return ResultBody.success("获取订单信息成功！", object);
		} catch (Exception e) {
			return ResultBody.error("获取订单信息失败！", null);
		}
	}
	
	@GetMapping("/listOrdersByUserId/{userId}")
	public ResultBody<JSONArray> listOrdersByUserId(@PathVariable("userId") String userId) {
		try {
			List<Orders> ordersList = ordersService.listOrdersByUserId(userId);
			if (ordersList.isEmpty()) {
				return ResultBody.success();
			}
			JSONArray re = new JSONArray();
			for (Orders orders : ordersList) {
				DeliveryAddress da = com.alibaba.fastjson.JSONObject.parseObject
						(JSON.toJSONString(daFeignClient.getDeliveryAddressById(orders.getDaId())), DeliveryAddress.class);

//				String daUrl = "http://localhost:10500/elm/DeliveryAddressController/getDeliveryAddressById/" + orders.getDaId();
//				DeliveryAddress da = com.alibaba.fastjson.JSONObject.parseObject(parseDataToObjStr(daUrl), DeliveryAddress.class);

				String address = da.getAddress();

				Business business = com.alibaba.fastjson.JSONObject.parseObject
						(JSON.toJSONString(businessFeignClient.getBusinessById(orders.getBusinessId())), Business.class);

//				String businessUrl = "http://localhost:10300/elm/BusinessController/getBusinessById/" + orders.getBusinessId();
//				Business business = com.alibaba.fastjson.JSONObject.parseObject(parseDataToObjStr(businessUrl), Business.class);

				List<OrderDetailet> detailets = ordersService.getOrderDetailetByOrderId(orders.getOrderId());
				List<BusinessOrderVO> businessOrderVOList = new ArrayList<>();

				for (OrderDetailet detailet : detailets) {
					BusinessOrderVO businessOrderVO = BusinessOrderVO.builder()
							.foodName(detailet.getFoodName())
							.foodPrice(detailet.getFoodPrice())
							.quantity(detailet.getQuantity()).build();
					businessOrderVOList.add(businessOrderVO);
				}

				JSONObject object = new JSONObject();
				object.putOpt("orderId", orders.getOrderId());
				object.putOpt("tel", orders.getUserId());
				object.putOpt("address", address);
				object.putOpt("businessName", business.getBusinessName());
				object.putOpt("businessAddress", business.getBusinessAddress());
				object.putOpt("totalPrice", orders.getOrderTotal());
				object.putOpt("deliveryPrice", business.getDeliveryPrice());
				object.putOpt("priceDetails", businessOrderVOList);
				object.putOpt("orderState", orders.getOrderState());

				re.add(object);
			}

			return ResultBody.success("获取成功！", re);
		} catch (Exception e) {
			return ResultBody.error("获取失败！", null);
		}
	}

	@PutMapping("/payment/{state}/{orderId}")
	public ResultBody<Object> updateOrderState(@PathVariable("state") Integer state,
											   @PathVariable("orderId") Integer orderId) {
		try {
			ordersService.updateOrderState(state,orderId);
			return ResultBody.success("支付成功", null);
		} catch (Exception e) {
			return ResultBody.error("支付失败", null);
		}
	}

	@GetMapping("/business/orders/{businessId}")
	public ResultBody<JSONArray> getBusinessOrders(@PathVariable("businessId") String businessId) {
		try {
			List<Orders> ordersList =  ordersService.listOrdersByBusinessId(businessId);
			if (ordersList.isEmpty()) {
				return ResultBody.error("获取失败！", null);
			}
			JSONArray re = new JSONArray();
			for (Orders o : ordersList) {
				JSONObject object = new JSONObject();

				User user = com.alibaba.fastjson.JSONObject.parseObject
						(JSON.toJSONString(userFeignClient.getUserInfoById(o.getUserId()).getResult()), User.class);

//				String userUrl = "http://localhost:10100/elm/UserController/user/info/" + o.getUserId();
//				User user = com.alibaba.fastjson.JSONObject.parseObject(parseDataToObjStr(userUrl), User.class);

				Business business = com.alibaba.fastjson.JSONObject.parseObject
						(JSON.toJSONString(businessFeignClient.getBusinessById(o.getBusinessId())), Business.class);

//				String businessUrl = "http://localhost:10300/elm/BusinessController/getBusinessById/" + o.getBusinessId();
//				Business business = com.alibaba.fastjson.JSONObject.parseObject(parseDataToObjStr(businessUrl), Business.class);

				Double deliveryPrice = business.getDeliveryPrice();
				List<OrderDetailet> orderDetailets = ordersService.getOrderDetailetByOrderId(o.getOrderId());
				List<BusinessOrderVO> list = new ArrayList<>();
				for (OrderDetailet od : orderDetailets) {
					BusinessOrderVO vo = BusinessOrderVO.builder()
							.foodName(od.getFoodName())
							.foodPrice(od.getFoodPrice())
							.quantity(od.getQuantity()).build();

					list.add(vo);
				}

				object.putOpt("userName", user.getUserName());
				object.putOpt("userId", user.getUserId());
				object.putOpt("orderDetail", list);
				object.putOpt("orderTotal", o.getOrderTotal());
				object.putOpt("deliveryPrice", deliveryPrice);
				object.putOpt("orderState", o.getOrderState());

				re.add(object);
			}
			return ResultBody.success("获取成功！", re);
		} catch (Exception e) {
			return ResultBody.error("获取失败！", null);
		}
	}

	@DeleteMapping("/user/cancelOrder/{orderId}")
	public ResultBody<Object> cancelOrder(@PathVariable("orderId") Integer orderId) {
		try {
			Orders orders = ordersService.getOrdersById(orderId);
			if (orders.getOrderState() == 0) {
				ordersService.cancelOrder(orderId);
				return ResultBody.success("订单已取消！", null);
			} else if (orders.getOrderState() == 1) {
				return ResultBody.error("已支付的订单不能直接取消，请联系商家！", null);
			}
			return ResultBody.error("不知道", null);
		} catch (Exception e) {
			return ResultBody.error("订单取消失败！", null);
		}
	}

//	private String parseDataToObjStr () {
//		Object obj = Objects.requireNonNull(restTemplate.getForObject
//				(url, ResultBody.class)).getResult();
//
//        return JSON.toJSONString(obj);
//	}
}
